package com.neusoft.eenie.signdemo.ui;

import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.neusoft.eenie.signdemo.R;
import com.neusoft.eenie.signdemo.adapter.HistoryAdapter;
import com.neusoft.eenie.signdemo.adapter.NameListAdapter;
import com.neusoft.eenie.signdemo.bean.HistoryInfo;
import com.neusoft.eenie.signdemo.bean.ParseInfo;
import com.neusoft.eenie.signdemo.bean.SignInfo;
import com.neusoft.eenie.signdemo.http.HttpUtiles;
import com.neusoft.eenie.signdemo.http.OKHttpUtiles;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class SignActivity extends BaseActivity {
    String TAG = "SignActivity";
    ListView nameList;
    Button btnSub;
    NameListAdapter listAdapter;
    EditText editInfo;
    List<SignInfo> infos = new ArrayList<>();
    ParseInfo parseInfo = new ParseInfo();
    String name;
    TextView txtWel;
    TextView txtInfo;
    List<HistoryInfo> historyInfos = new ArrayList<>();
    ListView hisList;
    HistoryAdapter historyAdapter;
    String midFlag;
    ActionBar actionBar;
    int flag = 1;//0代表添加、1代表更新
    int signFlag = 1;//0代表民意点名，1代表已经点名


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        actionBar = getSupportActionBar();

        midFlag = getIntent().getStringExtra("mid");
        if (midFlag.equals("check")) {
            actionBar.setTitle("今天尚未点名！");
            signFlag = 0;
        } else {
            actionBar.setTitle("今天已经点名！");
            parseInfo.setMid(midFlag);
            signFlag = 1;
        }

        initView();
        name = getIntent().getStringExtra("wel");
        txtWel.setText(name);
        getHistory();
    }

    private void initView() {
        hisList = (ListView) findViewById(R.id.hisList);
        historyAdapter = new HistoryAdapter(this, historyInfos);
        hisList.setAdapter(historyAdapter);
        hisList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                flag = 1;
                txtInfo.setText(parseInfo.getRoomName() + "\n信息更新中...");
                String link = historyInfos.get(position).getLink();
                getInfos(link);
                parseInfo.setMid(link.substring(link.lastIndexOf("/") + 1));
            }
        });


        txtInfo = (TextView) findViewById(R.id.txtInfo);
        editInfo = (EditText) findViewById(R.id.editInfo);
        nameList = (ListView) findViewById(R.id.nameList);
        listAdapter = new NameListAdapter(this, new ArrayList<SignInfo>());
        nameList.setAdapter(listAdapter);
        btnSub = (Button) findViewById(R.id.btnSub);
        btnSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                parseInfo.setCheck_info(editInfo.getText().toString().trim());
                commit(parseInfo);
            }
        });


        txtWel = (TextView) findViewById(R.id.txtWel);

    }


    public void getInfos(String link) {

        OKHttpUtiles.getInstance().get(link, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                btnSub.post(new Runnable() {
                    @Override
                    public void run() {
                        showDialog("加载寝室成员失败", true);
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    Document doc = Jsoup.parse(response.body().string());
                    parseInfo.setRoomName(doc.getElementsByClass("alert").text());
                    parseInfo.setDmdate(doc.getElementsByTag("option").get(0).text());
                    parseInfo.setCheck_info(doc.getElementById("check_info").text());
                    Elements elements = doc.getElementsByClass("check_wbk");


                    infos.clear();
                    for (Element e : elements) {
                        SignInfo info = new SignInfo();
                        info.setName(e.getElementsByClass("check_block").text());
                        info.setId(e.getElementsByTag("input").attr("value"));
                        if (e.getElementsByClass("icheck_style").hasAttr("checked")) {
                            info.setCheck(true);
                        } else {
                            info.setCheck(false);
                        }
                        infos.add(info);
                    }
                    parseInfo.setInfos(infos);
                    btnSub.post(new Runnable() {
                        @Override
                        public void run() {
                            listAdapter.replaceData(infos);
                            listAdapter.notifyDataSetChanged();
                        }
                    });

                    btnSub.post(new Runnable() {
                        @Override
                        public void run() {
                            editInfo.setText(parseInfo.getCheck_info());
                            txtInfo.setText(parseInfo.getRoomName() + "\n" + parseInfo.getDmdate());
                            missDialog();
                        }
                    });
                }


            }
        });
    }

    public void commit(ParseInfo parse) {
        showDialog("正在提交...");
        RequestBody body = RequestBody.create(OKHttpUtiles.formReq, parseToStr(parse));
        String url = "";

        if (flag == 1) {
            url = HttpUtiles.URL_COMMIT;
        } else {
            url = HttpUtiles.URL_COMMIT_ADD;
        }


        OKHttpUtiles.getInstance().post(url, body, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                btnSub.post(new Runnable() {
                    @Override
                    public void run() {
                        showDialog("提交失败", true);
                    }
                });

            }

            @Override
            public void onResponse(Response response) throws IOException {
                btnSub.post(new Runnable() {
                    @Override
                    public void run() {


                        if (signFlag == 0 && flag == 0) {

                            signFlag = 1;
                            actionBar.setTitle("今天已经点名！");
                        }

                        getHistory();
                        showDialog("提交成功", true);
                    }
                });

            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.sign_mune, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.refresh:
                getHistory();
                break;
            case R.id.sign:

                if (signFlag == 0) {
                    flag = 0;
                    getInfos(HttpUtiles.URL_LOAD_CHECK);
                } else {
                    showDialog("点你妹~！没看到标题说点过啦？？！", true);
                }

                break;
        }
        return super.onOptionsItemSelected(item);
    }


    public String parseToStr(ParseInfo info) {
        try {
//        dmdate=2016-03-25&ck%5B%5D=11750&ck%5B%5D=12252&ck%5B%5D=12253&ck%5B%5D=12254&ck%5B%5D=12255&mid=327254&check_info=12sa
            StringBuffer sb = new StringBuffer();
            sb.append("dmdate=" + info.getDmdate() + "&");
            for (SignInfo signInfo : parseInfo.getInfos()) {
                if (signInfo.isCheck()) {
                    sb.append("ck%5B%5D=" + URLEncoder.encode(signInfo.getId(), "UTF-8") + "&");
                }
            }
            sb.append("mid=" + URLEncoder.encode(parseInfo.getMid(), "UTF-8") + "&");
            sb.append("check_info=" + URLEncoder.encode(parseInfo.getCheck_info(), "UTF-8"));
            return sb.toString();
        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        }
        return "";
    }


    public void getHistory() {
        OKHttpUtiles.getInstance().get(HttpUtiles.URL_LOAD_HISTORY, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {

                if (response.isSuccessful()) {


                    parseHistory(response.body().string());
                }

            }
        });
    }


    public void parseHistory(String str) {
        historyInfos.clear();
        Document doc = Jsoup.parse(str);
        Elements ele = doc.getElementsByTag("ul");
        for (Element e : ele.get(0).getElementsByTag("a")) {
            HistoryInfo info = new HistoryInfo();
            info.setLink(e.attr("href"));

            String s = e.getElementsByClass("badge").text();
            info.setStatue(s);
            if (!s.equals("全勤")) {
                info.setFull(false);
            }
            info.setDate(e.text().substring(s.length()));
            historyInfos.add(info);
        }
        btnSub.post(new Runnable() {
            @Override
            public void run() {
                historyAdapter.replaceData(historyInfos);
                historyAdapter.notifyDataSetChanged();
            }
        });
    }


}
